package com.luo.d3s.light.jpa.ec.infrastructure.database.specification;

import com.luo.d3s.light.jpa.ec.application.dto.query.GoodsTagPageQuery;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.*;
import java.util.List;
import java.util.Objects;

/**
 * 商品标签分页列表查询条件（Spring Data JPA）
 *
 * @author luohq
 * @date 2023-08-03
 */
public class GoodsTagPageQuerySpecification implements Specification {

    private GoodsTagPageQuery goodsTagPageQuery;

    public GoodsTagPageQuerySpecification(GoodsTagPageQuery goodsTagPageQuery) {
        this.goodsTagPageQuery = goodsTagPageQuery;
    }

    @Override
    public Predicate toPredicate(Root root, CriteriaQuery cq, CriteriaBuilder cb) {

        Predicate conjunctionPredicate = cb.conjunction();
        List<Expression<Boolean>> expressions = conjunctionPredicate.getExpressions();
        //tag_name like %:tagName% and create_time >= :createTimeStart and create_time <= :createTimeEnd
        if (Objects.nonNull(this.goodsTagPageQuery.getTagName())) {
            //String.format中可使用%%来转义%
            expressions.add(cb.like(root.get("tagName"), String.format("%%%s%%", this.goodsTagPageQuery.getTagName())));
        }
        if (Objects.nonNull(this.goodsTagPageQuery.getCreateTimeStart())) {
            expressions.add(cb.greaterThanOrEqualTo(root.get("createTime"), this.goodsTagPageQuery.getCreateTimeStart()));
        }
        if (Objects.nonNull(this.goodsTagPageQuery.getCreateTimeEnd())) {
            expressions.add(cb.lessThanOrEqualTo(root.get("createTime"), this.goodsTagPageQuery.getCreateTimeEnd()));
        }
        return conjunctionPredicate;
    }
}
